package com.JudgeOnline.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class login extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");

		String tea_ID = request.getParameter("tea_ID");
		String password = request.getParameter("password");
		String driverName = "com.mysql.jdbc.Driver"; // 数据库的
		String dbURL = "jdbc:mysql://localhost:3306/judge_online";
		String userName = "root";
		String userPwd = "123456";
		Connection conn;

		if (!tea_ID.equals("") && tea_ID != null && !password.equals("")
				&& password != null) {
			try {
				// 连接数据库
				Class.forName(driverName);
				conn = DriverManager.getConnection(dbURL, userName, userPwd);

				String sql = "select * from teacher where tea_ID=? and password=?";
				PreparedStatement pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, tea_ID);
				pstmt.setString(2, password);
				ResultSet rs = pstmt.executeQuery();

				if (rs.next()) {
					session.setAttribute("login", "yes"); // 验证通过之后，跳转到后续页面
					session.setAttribute("tea_ID", tea_ID);
					if (tea_ID.equals("admin"))
						response.sendRedirect("../admin.jsp");
					else
						response.sendRedirect("../main.jsp");
				} else {
					request.setAttribute("message", "工号或密码错误！");
					request.getRequestDispatcher("/index.jsp").forward(request,
							response);
				}
			} catch (Exception ee) {
				ee.printStackTrace();
			}
		} else {
			request.setAttribute("message", "工号或密码不能为空！");
			request.getRequestDispatcher("/index.jsp").forward(request,
					response);
		}

		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

}
